package com.app.micaihu.view.newsdetail.fragment;


import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.fragment.app.Fragment;
import androidx.viewpager.widget.ViewPager;

import com.android.volley.VolleyError;
import com.app.micaihu.R;
import com.app.micaihu.adapter.NewsFragmentPagerAdapter;
import com.app.micaihu.base.BaseOldActivity;
import com.app.micaihu.base.BaseOldFragment;
import com.app.micaihu.base.bean.DataBean;
import com.app.micaihu.bean.news.VideoRoomNewsList;
import com.app.micaihu.bean.news.VideoShow;
import com.app.micaihu.configure.Config;
import com.app.micaihu.configure.URIContant;
import com.app.micaihu.custom.view.ColumnHorizontalScrollView;
import com.app.widget.LoadView;
import com.app.micaihu.listener.HttpListener;
import com.app.micaihu.utils.HttpUtils;
import com.app.micaihu.view.newsdetail.VideoShowActivity;
import com.app.utils.util.ViewSizeUtils;
import com.google.gson.reflect.TypeToken;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 视频剧集frgment
 * Created by linkai on 2016/7/14.
 */
public class VideoShowFragment extends BaseOldFragment implements ViewPager.OnPageChangeListener, View.OnClickListener {

    private Activity mActivity;
    private ViewGroup mContentView;//根布局

    /************
     * 页面控件
     *************/
    private ColumnHorizontalScrollView mColumnHorizontalScrollView;
    private LinearLayout mRadioGroup_content;
    private RelativeLayout rl_column;
    private ViewPager mViewPager;
    public ImageView shade_left;
    public ImageView shade_right;
    private LoadView loadView2;

    /************
     * 逻辑数据
     *************/
    private List<VideoShow> videoShowList;//栏目列表
    private int columnSelectIndex = 0;//当前选中的栏目
    private int mScreenWidth = 0;//屏幕宽度
    private ArrayList<Fragment> fragments = new ArrayList<Fragment>();//新闻页面集合

    private String id;


    public VideoShowFragment() {
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        Bundle args = getArguments();
        id = (args != null ? args.getString(Config.Extra.PARAMETER1, "") : "");
        super.onCreate(savedInstanceState);
    }

    @Override
    public void onAttach(Activity activity) {
        this.mActivity = activity;
        super.onAttach(activity);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        if (mContentView == null) {
            mContentView = (ViewGroup) inflater.inflate(R.layout.fragment_videoshow, null);
            initView();
        }
        return mContentView;
    }


    /**
     * 初始化layout控件
     */
    private void initView() {
        mColumnHorizontalScrollView = (ColumnHorizontalScrollView) mContentView
                .findViewById(R.id.mColumnHorizontalScrollView);
        mRadioGroup_content = (LinearLayout) mContentView
                .findViewById(R.id.mRadioGroup_content);
        rl_column = (RelativeLayout) mContentView.findViewById(R.id.rl_column);
        mViewPager = (ViewPager) mContentView.findViewById(R.id.mViewPager);
        shade_left = (ImageView) mContentView.findViewById(R.id.shade_left);
        shade_right = (ImageView) mContentView.findViewById(R.id.shade_right);
        loadView2 = (LoadView) mContentView.findViewById(R.id.ld_loadview);
        loadView2.setErrorPageClickListener(this);
        loadData();
    }

    private void loadData() {
        Map<String, String> parms = new HashMap<>();
        parms.put("id", id);
        HttpListener<DataBean<VideoRoomNewsList>> httpListener = new HttpListener<DataBean<VideoRoomNewsList>>() {
            @Override
            public void onStart() {
                if (loadView2 != null) {
                    loadView2.showLoadPage("");
                }
            }

            @Override
            public void onError(VolleyError error) {
                if (loadView2 != null) {
                    loadView2.showErrorPage();
                }
            }

            @Override
            public void onSuccess(DataBean<VideoRoomNewsList> response) {

                if (response.noError()) {
                    VideoRoomNewsList videoRoomNewsList = response.getData();
                    if (videoRoomNewsList != null) {
                        videoShowList = videoRoomNewsList.getSetList();
                        setChangelView();
                        if (loadView2 != null) {
                            loadView2.showSuccess();
                        }
                        if (getActivity() != null && getActivity() instanceof VideoShowActivity) {
                            //设置activity的分享数据
                            ((VideoShowActivity) getActivity()).setShareData(videoRoomNewsList.getColumnInfo());
                        }
                    } else {
                        if (loadView2 != null) {
                            loadView2.showErrorPage("暂无视频");
                        }
                    }
                } else {
                    if (loadView2 != null) {
                        loadView2.showErrorPage(response.getNnderstoodMsg());
                    }
                }
            }
        };
        HttpUtils.addPostCacheRequest(URIContant.VIDEO_ROOM, new TypeToken<DataBean<VideoRoomNewsList>>() {
        }.getType(), "", parms, httpListener);
    }


    /**
     * 初始化栏目项时候调用
     */
    public void setChangelView() {
        initTabColumn();
        initFragment();
    }


    /**
     * 初始化Column栏目项
     */
    private void initTabColumn() {
        if (videoShowList == null && videoShowList.size() > 0) {
            return;
        }
        mScreenWidth = ViewSizeUtils.getWidthPixels();
        mRadioGroup_content.removeAllViews();
        int count = videoShowList.size();
        mColumnHorizontalScrollView.setParam(mActivity, mScreenWidth, count,
                mRadioGroup_content, shade_left, shade_right,
                rl_column);
        int itemWidth = mColumnHorizontalScrollView.getItemWidth();
        LayoutInflater inflayouter = mActivity.getLayoutInflater();
        for (int i = 0; i < count; i++) {
            final String chanelname = videoShowList.get(i).getSetTitle();
            LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(
                    itemWidth,
                    LinearLayout.LayoutParams.WRAP_CONTENT);
            TextView columnTextView = (TextView) inflayouter.inflate(R.layout.layout_scroll_text, null);
            columnTextView.setTextAppearance(mActivity,
                    R.style.top_category_scroll_view_item_text);

            columnTextView.setText(chanelname);
            if (columnSelectIndex == i) {
                columnTextView.setSelected(true);
            }
            columnTextView.setOnClickListener(new View.OnClickListener() {

                @Override
                public void onClick(View v) {
                    for (int i = 0; i < mRadioGroup_content.getChildCount(); i++) {
                        View localView = mRadioGroup_content.getChildAt(i);
                        if (localView != v) {
                            localView.setSelected(false);
                        } else {
                            localView.setSelected(true);
                            mViewPager.setCurrentItem(i);
                            if (v != null && v.getTag() != null) {
                                flushCurrentPage();
                            } else if (v != null) {
                                v.setTag("true");
                            }
                        }
                    }
                }
            });
            if (count > 4) {
                columnTextView.setPadding(20, 5, 20, 5);
                mRadioGroup_content.addView(columnTextView, i);
            } else {
                mRadioGroup_content.addView(columnTextView, i, params);
            }
        }
    }

    /**
     * 选择的Column里面的Tab
     */
    private void selectTab(int tab_postion) {
        columnSelectIndex = tab_postion;

        if (videoShowList != null && videoShowList.size() > 5) {
            for (int i = 0; i < mRadioGroup_content.getChildCount(); i++) {
                View checkView = mRadioGroup_content.getChildAt(tab_postion);
                int k = checkView.getMeasuredWidth();
                int l = checkView.getLeft();
                int i2 = l + k / 2 - mScreenWidth / 2;
                // rg_nav_content.getParent()).smoothScrollTo(i2, 0);
                mColumnHorizontalScrollView.smoothScrollTo(i2, 0);
                // mColumnHorizontalScrollView.smoothScrollTo((position - 2) *
                // mItemWidth , 0);
            }
        }

        // 判断是否选中
        for (int j = 0; j < mRadioGroup_content.getChildCount(); j++) {
            View checkView = mRadioGroup_content.getChildAt(j);
            boolean ischeck;
            if (j == tab_postion) {
                ischeck = true;
            } else {
                ischeck = false;
            }
            checkView.setSelected(ischeck);
        }
    }

    /**
     * 初始化Fragment新闻页面
     */
    private void initFragment() {
        if (videoShowList == null) {
            return;
        }
        fragments.clear();// 清空
        int count = videoShowList.size();
        for (int i = 0; i < count; i++) {
            Bundle data = new Bundle();
            data.putString(Config.Extra.PARAMETER1, id);
            data.putString(Config.Extra.PARAMETER2, videoShowList.get(i).getSetNum());
            VideoShowListFragment newfragment = new VideoShowListFragment();
            newfragment.setArguments(data);
            newfragment.setHandler(handler);//设置外部操作
            fragments.add(newfragment);
        }
        // 开始适配
        NewsFragmentPagerAdapter mAdapetr = new NewsFragmentPagerAdapter(
                getChildFragmentManager(), fragments);
        // mViewPager.setOffscreenPageLimit(0);
        mViewPager.setAdapter(mAdapetr);
        mViewPager.setOnPageChangeListener(this);
        mViewPager.setCurrentItem(0);
    }

    /* 刷新当前页面数据 */
    public void flushCurrentPage() {
        if (fragments == null || mViewPager == null) {
            return;
        }

        if (fragments.get(mViewPager.getCurrentItem()) instanceof VideoShowListFragment) {
            VideoShowListFragment currentFragment = (VideoShowListFragment) fragments.get(mViewPager.getCurrentItem());
            if (currentFragment != null) {
                currentFragment.flushData();
            }
        }

    }

    /**
     * 这是外部handler
     */
    private Handler handler;

    public void setHandler(Handler handler) {
        this.handler = handler;
    }

    @Override
    public void onPageScrollStateChanged(int arg0) {
    }


    @Override
    public void onPageScrolled(int arg0, float arg1, int arg2) {
    }

    @Override
    public void onPageSelected(int position) {
        selectTab(position);
    }


    @Override
    public void onClick(View v) {
        if (v == null) {
            return;
        }
        if (v.getId() == R.id.error_page) {
            loadData();
        }
    }
}
